package com.example.util;

import ch.qos.logback.classic.Logger;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.*;
import com.example.mapp.*;
import com.example.service.ElevatorService;
import com.example.service.PartyService;
import com.example.service.StatisticsService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by simon on 2017/10/3.
 */
@Component
@Configurable
@PropertySource({"classpath:application.properties"})
@EnableScheduling
public class TaskUtil {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(TaskUtil.class);

	@Value("${jpush.appkey}")
	private String appkey;

    @Value("${jpush.masterSecret}")
	private String masterSecret;

	@Autowired
	StatisticsService statisticsService;

	@Autowired
	ElevatorService elevatorService;

	@Autowired
	PartyService partyService;

	@Autowired
	private MessageNoticeMapp messageNoticeMapp;

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private Environment environment;

	@Autowired
	StatisticsMapp statisticsMapp;
	
	@Autowired
    ElevatorMapp elevatorMapp;

	@Autowired
	PartyMapp partyMapp;

	/**
	 * 每天7点发送维保通知
	 */
	@Scheduled(cron = "0 0 7 * * ? ")
	public void pushNotice() {
		boolean openstak = environment.getProperty("opentask", Boolean.class);
		if (!openstak) {
			return;
		}
		try {
			Map<String, Object> result = statisticsService.findNotice();
			if ((result.get("status") + "").equals("505")) {
				return;
			}
			List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("data");
			String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			Set<String> maintSet = new HashSet<>();
			Set<String> yearMaintSet = new HashSet<>();

			for (Map<String, Object> tmp : list) {
				String statusId = tmp.get("status_id") != null ? tmp.get("status_id") + "" : "";
				String outsideNum = tmp.get("outside_num") != null ? tmp.get("outside_num") + "" : "";
				String safeUserId = tmp.get("safe_user_id") != null ? tmp.get("safe_user_id") + "" : "";
				String usedPartyId = tmp.get("used_party_id") != null ? tmp.get("used_party_id") + "" : "";
				String elevatorStreet = tmp.get("elevator_street") != null ? tmp.get("elevator_street") + "" : "";
				String elevatorAddr = tmp.get("elevator_addr") != null ? tmp.get("elevator_addr") + "" : "";
				String elevatorNum = tmp.get("elevator_num") != null ? tmp.get("elevator_num") + "" : "";
				String maintDate = tmp.get("maint_date") != null ? tmp.get("maint_date") + "" : "";
				String buildAddr = tmp.get("build_addr") != null ? tmp.get("maint_date") + "的" : "";
				String content = buildAddr + "外部关联码为：" + outsideNum + " 的电梯," + "应于" + maintDate;
				String title = "";
				if (null == safeUserId || "".equals(safeUserId)) {
					continue;
				}
				if ("0".equals(statusId)) {
					title = "电梯将维保通知";
					content = content + "进行维保，请尽快处理。";
				} else if ("1".equals(statusId)) {
					title = "电梯维保过期通知";
					content = content + "进行维保，现已过期。";
					maintSet.add(elevatorNum);
				} else if ("3".equals(statusId)) { //年度定期检验
					title = "电梯将年检通知";
					content = content + "进行年检，请尽快处理。";
				} else if ("4".equals(statusId)) {
					title = "电梯年检超期通知";
					content = content + "进行定检，现已过期。";
					yearMaintSet.add(elevatorNum);
				}
				JpushUtil js = new JpushUtil(appkey, masterSecret, content, title);
				List<String> deviceIds = new ArrayList<>();
				if (null != tmp.get("register_id") && !tmp.get("register_id").equals("")) {
					deviceIds.add(tmp.get("register_id") + "");
				}
				if (deviceIds != null && deviceIds.size() > 0) {
					js.sendPushAll(true, deviceIds);
				}
				MessageNotice msg = new MessageNotice();
				msg.setTitle(title);
				msg.setContent(content);
				//msg.setSendUserId("");
				msg.setReceiveUserId(safeUserId);
				msg.setIsRead("0");
				msg.setNoticeTime(noticeTime);
				msg.setReceivePartyId(usedPartyId);
				messageNoticeMapp.add(msg);
			}
			for (String tmp : maintSet) {
				Elevator elevator = elevatorMapp.queryByElevatorNum(tmp);
				if (null != elevator.getMaintenancePartyId()) {
					PromotionUtil.calcParty(promotionMapp, -200, "1", elevator.getMaintenancePartyId(), "收到维保过期提示1条", "0");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}

	/**
	 * 首页年度统计信息
 	 */
	@Scheduled(cron = "0 0 0 1 1/3 ? ")
	public void quarterStatistics() {
		boolean openstak = environment.getProperty("opentask",Boolean.class);
		if(!openstak){
			return;
		}
		try {
			statisticsMapp.insertImplementation();
			statisticsMapp.insertRepair();
			statisticsMapp.insertMaintOvertime();
			statisticsMapp.insertCheckOvertime2();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
	}

	/**
	 * 定时发送给和苏单位的接口
	 */
	/*@Scheduled(cron = "0 0 1 * * ?")*/
	public void sendMessages() {
		boolean openstak = environment.getProperty("opentask", Boolean.class);
		if (!openstak) {
			return;
		}
		// 维保单位
		List<Map<String, String>> maintenanceList = new ArrayList<>();
		// 使用单位
		List<Map<String, String>> userList = new ArrayList<>();

		// 获取维保单位的积分信息
		List<Map<String, String>> unitmarks = partyMapp.getCompanyMarksInfo();
		if (unitmarks != null && unitmarks.size() > 0) {
			for (Map<String, String> unitEntry : unitmarks) {
				Map<String, String> param = new HashMap<>();
				param.put("com_reg_no", unitEntry.get("creditCode"));
				param.put("com_score", unitEntry.get("mark"));
				param.put("data_time", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				if ("1".equals(unitEntry.get("partyType"))) {
					param.put("com_name", unitEntry.get("partyName"));
					maintenanceList.add(param);
				} else {
					param.put("use_com_name", unitEntry.get("partyName"));
					userList.add(param);
				}
			}
		}
		// 维保单位发送接口
		Map<String, Object> maintenanceMap = new HashMap<>();
		maintenanceMap.put("lms_com_score", maintenanceList);
		String httpUrl = "http://dev.hesutech.com:81/bpalercxdi/lms/lms_com_score";
		JSONObject jsonObject = new JSONObject(maintenanceMap);
		HttpRequestUtils.sendPost(httpUrl, jsonObject, null);

		// 使用单位发送接口
		Map<String, Object> useMap = new HashMap<>();
		useMap.put("lms_use_com_score", userList);
		String url = "http://dev.hesutech.com:81/bpalercxdi/lms/lms_use_com_score";
		JSONObject json = new JSONObject(useMap);
		HttpRequestUtils.sendPost(url, json, null);
	}

	/*@Scheduled(cron = "0 0/5 * * * ?")*/
	public void openstaksendMessages() {
		boolean openstak = environment.getProperty("opentask", Boolean.class);
		if (!openstak) {
			return;
		}
		elevatorService.findTest();
	}

	/**
	 * 每天1点跑机构信息
	 */
	@Scheduled(cron = "0 0 1 * * ?")
	public void openstakPartyCensusInfo() {
		boolean openstak = environment.getProperty("opentask", Boolean.class);
		if (!openstak) {
			return;
		}
		partyService.partyCensusInfo();
	}
}
